package 尚硅谷juc大厂.test18;


/**
 * 卖房子案例
 */
class House{
    ThreadLocal<Integer> threadLocal=ThreadLocal.withInitial(()->0);

    /**
     * 卖出一套房子
     */
    public void saleHouse(){
        Integer value = threadLocal.get();
        ++value;
        threadLocal.set(value);
    }
}

public class Test18 {

    public static void main(String[] args) {
        House house=new House();
        new Thread(()->{
            try {
                for (int i=0;i<3;i++){
                    house.saleHouse();
                    System.out.println(Thread.currentThread().getName()+"销售卖出\t"+house.threadLocal.get()+"套");
                }
            }catch (Exception exception){

            }finally {
                /**
                 * 必须调用remove()方法
                 */
                house.threadLocal.remove();
            }
        },"t1").start();

        new Thread(()->{
            for (int i=0;i<6;i++){
                house.saleHouse();
            }
            System.out.println(Thread.currentThread().getName()+"销售卖出\t"+house.threadLocal.get()+"套");
        },"t2").start();

        new Thread(()->{
            for (int i=0;i<8;i++){
                house.saleHouse();
            }
            System.out.println(Thread.currentThread().getName()+"销售卖出\t"+house.threadLocal.get()+"套");
        },"t3").start();

        System.out.println(Thread.currentThread().getName()+"销售卖出\t"+house.threadLocal.get()+"套");
    }
}
